package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.mapper.CheckItemMapper;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.service.CheckItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 *
 * @author sot
 * @description 检查组service实现类
 **/
@Slf4j
@Service
public class CheckItemServiceImpl implements CheckItemService {
    @Autowired
    private CheckItemMapper checkItemMapper;

    /**
     * 添加检查项
     * @param checkItem 检查项
     */
    @Transactional
    @Override
    public void add(CheckItem checkItem) {
        log.info("[检查项-添加]data：{}",checkItem);
        //判断参数是否非法
        if (checkItem.getCode()==null|| StringUtils.isEmpty(checkItem.getName())){
            throw new BusinessRuntimeException(MessageConst.ADD_CHECKITEM_FAIL);
        }
        checkItemMapper.insert(checkItem);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        log.info("[检查项-分页查询]data：{}",queryPageBean);
        //使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        // 分页查询数据库
        Page<CheckItem> page = checkItemMapper.selectByConditon(queryPageBean.getQueryString());

        //封装分页数据
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 根据id删除检查项
     * @param id 数据id
     */
    @Transactional
    @Override
    public void delete(int id) {
        log.info("[检查项-根据id删除]id：{}",id);
        //判断id值是否为空
        if (id<=0){
            throw new BusinessRuntimeException("参数非法");
        }

        //查看检查项组中是否有关联的检查项，如果有不能删除
       int sum = checkItemMapper.checkGruoup(id);

       if (sum>=0){
           throw new BusinessRuntimeException("检查组中存在检查查项目，不可删除");
       }
        //实际删除操作
        checkItemMapper.deleteById(id);
    }

    /**
     * 修改检查项
     * @param checkItem 检查组
     */
    @Transactional
    @Override
    public void edit(CheckItem checkItem) {
        log.info("[检查项-编辑]data:{}",checkItem);
        //TODO 检查修改的参数是否非法
        checkItemMapper.update(checkItem);
    }

    @Override
    public CheckItem findById(Integer id) {
        log.info("[检查项-根据ID查询]id:{}",id);
        return checkItemMapper.selectById(id);
    }

    @Override
    public List<CheckItem> findAll() {
        log.info("[检查项-查询所有]");
        return checkItemMapper.selectAll();
    }
}
